package core;

import gitobject.Commit;
import gitobject.GitObject;
import gitobject.Tree;
import picocli.CommandLine.Command;
import picocli.CommandLine.Parameters;
import picocli.CommandLine.Option;
import repository.Branch;
import repository.Index;
import repository.Repository;
import utility.Utility;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;

@Command(
        name = "checkout"
)
/**
 * 实现jit checkout -分支命令
 */
public class JitCheckout implements Runnable {
    @Parameters(paramLabel = "<branch name>", description = {"The Branch Name you want to create or delete"}, defaultValue = "")
    private String branch_name;

    @Option(names = {"-b"}, description = "create and checkout a new branch")
    boolean need_create;

    @Override
    public void run() {
        if(branch_name.equals("")){
            branch_name = Repository.getInstance().getCurrentBranch().getName();
        }
        if (need_create) {
            // 创建并切换
            Branch branch = Branch.create(branch_name);
            Repository.getInstance().setCurrentBranch(branch);
        } else {
            Branch branch = Branch.findByName(branch_name);
            if (branch.getCommit() == null) {
                System.err.printf("error: pathspec '%s' did not match any file(s) known to git%n", branch_name);
            }
            Repository repo = Repository.getInstance();
            Branch cur = repo.getCurrentBranch();
            repo.setCurrentBranch(branch);
            try {
                Commit commit = (Commit) GitObject.findByKey(branch.getCommit());
                Index index = Repository.getInstance().getIndex();
                List<Path> need_remove = index.switchTo(commit.getKey());// 切换Index，并获取需要删除的文件
                // 删除文件
                for (Path path : need_remove) {
                    path = repo.getWorkTree().resolve(path);
                    if (!path.toFile().delete()) {
                        System.err.printf("Fatal: failed to delete %s", path);
                    }
                }
                Tree tree = (Tree) GitObject.findByKey(commit.getTree());
                tree.restoreContent();
                index.write();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
